function postAjax(url, data, cb) {
  chrome.storage.sync.get(['token'], function (result) {
    let token = result.token;
    let xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("token", token);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            cb(xhr.responseText);
        }
    };
    data = JSON.stringify(data);
    if (data.length === 0) {
      xhr.send();
      return false;
    }
    xhr.send(data);
  });
}
function getAjax(url, data, cb) {
  chrome.storage.sync.get(['token'], function (result){
    let token = result.token;
    $.ajax({
      url: url,
      type: "get",
      data: data,
      contentType: "application/json",
      dataType: "json",
      headers: {
        "token": token
      },
      success: function(data) {
        cb(data);
      },
      error: function (err) {
        console.log(err);
      }
    })
  });
}
function getPunishOrdersAjax(url, data, orginData, cb) {
  $.ajax({
    url: url,
    type: "get",
    data: data,
    contentType: "application/json",
    dataType: "json",
    success: function(result) {
      let data = {result: result, orginData: orginData};
      cb(data);
    },
    error: function (err) {
      setTimeout(function(){
        getPunishOrdersAjax(url, data, orginData, cb);
      }, 3000);
    }
  });
}
function getRDWwTabsCount(callback) {
  chrome.tabs.query({}, function(tabs){
    let count = 0;
    for (let i in tabs) {
      if (tabs[i]['url'].indexOf("://healthcenter.taobao.com") >= 0 ||
        tabs[i]['url'].indexOf("://mai.taobao.com/seller_admin.htm") >= 0 ||
        tabs[i]['url'].indexOf("://myseller.taobao.com/home.htm") >= 0
       ) {
        count++;
      }
    }
    console.log(count);
    callback(count);
  });
}
let bgUtils = {
  rand: function (number) {
    let t = new Date();
    let s = t.getTime();
    s = ( s * 9301 + 49297 ) % 233280;
    let temp = s / ( 233280.0 );
    return Math.ceil(temp * number);
  },
  parseUrlArg: function(str) {
    if (typeof(str) == 'string') {
      let str_len = str.length;
      let str_ret = '';
      for (let i = 0; i < str_len; i++) {
        if (i % 2 == 0) {
          str_ret += str[i];
        }
      }
      let random_str = bgUtils.rand(2) + '.' + bgUtils.rand(100) + '.' + bgUtils.rand(999);
      let end_str = str_ret.slice(0, 6).toUpperCase();
      let start_str = str_ret.slice(-5);
      str_ret = start_str + '.' + random_str + '.' + end_str;
      return str_ret;
    } else {
      return false;
    }
  },
  getUrlArg: function (_url) {
    let parmas = {};
    let url = '';
    let tmp;
    if (_url.indexOf('?') > 0) {
        tmp = _url.split("?");
        url = tmp[0];
        tmp = tmp[1];
    } else {
        url = _url;
    }
    if (tmp && tmp.indexOf('&') > 0) {
        tmp = tmp.split("&");
        for (let i in tmp) {
            if (tmp[i].split('=')[1] && tmp[i].split('=')[1].indexOf('#') > 0) {
                parmas[tmp[i].split('=')[0]] = tmp[i].split('=')[1].split('#')[0];
            } else {
                parmas[tmp[i].split('=')[0]] = tmp[i].split('=')[1];
            }
        }
    } else if (tmp) {
        if (tmp.split('=').length === 2) {
            if (tmp.split('=')[1].indexOf('#') > 0) {
                parmas[tmp.split('=')[0]] = tmp.split('=')[1].split('#')[0];
            } else {
                parmas[tmp.split('=')[0]] = tmp.split('=')[1];
            }
        }
    }
    return parmas;
  },
  changeUrlArg: function (url, arg, value) {
    let reg = new RegExp("([?&]" + arg + ")=[^&]+", "gmi");
    if (reg.test(url)) {
        url = url.replace(reg, "$1=" + value);
    } else {
        if (url.indexOf("?") === -1) {
            url += "?";
        } else {
            url += "&";
        }
        url += arg + "=" + value;
    }
    return url;
  }
};

let isOpera = !!window.opera || -1 < navigator.userAgent.indexOf(" OPR/");
let isFirefox = -1 < navigator.userAgent.toLowerCase().indexOf("firefox");
let isChrome = !isOpera && !isFirefox;
let chromeVersion = /Chrome\/([0-9]+)/.exec(navigator.userAgent)[1];
let optUrls = ['*://api.feimadianshang.com/plugin/*', '*://trade.taobao.com/trade/itemlist/*', '*://healthcenter.taobao.com/home/json/*', '*://sycm.taobao.com/mc/ci/item/*'];
let optExtraInfoSpec = ["requestHeaders", "blocking"];
if (isChrome && chromeVersion >= 72) optExtraInfoSpec.push('extraHeaders');

chrome.webRequest.onBeforeSendHeaders.addListener(function (details) {
  let gotRef = false;
  for (let n in details.requestHeaders) {
    gotRef = details.requestHeaders[n].name.toLowerCase() == 'referer';
    if(gotRef){
      let request_url = details.url;
      let ref = details.requestHeaders[n].value;
      let reqArg = bgUtils.getUrlArg(request_url);
      let newRef = bgUtils.changeUrlArg(ref, 'spm', bgUtils.parseUrlArg(reqArg.sign));
      details.requestHeaders[n].value = newRef;
      break;
    }
  }
  if (!gotRef) {
    let request_url = details.url;
    if (request_url.indexOf('api.feimadianshang.com') >= 0) {
        let reqArg = bgUtils.getUrlArg(request_url);
        let spm = bgUtils.parseUrlArg(reqArg.sign);
        if(spm != undefined){
            details.requestHeaders.push({name: 'Referer', value: 'https://www.taobao.com?spm=' + spm});
        }
    }
    if(request_url.indexOf('https://trade.taobao.com/trade/itemlist/asyncSold.do') >= 0) {
        details.requestHeaders.push({name: 'Referer', value: 'https://trade.taobao.com'});
    }
    if (request_url.indexOf('https://healthcenter.taobao.com/home/json/GetPunishHistory.json?_x=1') >= 0 || request_url.indexOf('https://healthcenter.taobao.com/home/json/get_affect_order_list.do?_x=1') >= 0) {
        details.requestHeaders.push({name: 'Referer', value: 'https://healthcenter.taobao.com'})
    }
    if(request_url.indexOf('https://sycm.taobao.com/mc/ci/item/trend.json') >= 0) {
        details.requestHeaders.push({name: 'Referer', value: 'https://sycm.taobao.com/mobile/index.htm'});
        details.requestHeaders.push({name: 'Transit-Id', value: 'a78Wj9HovMFDTibrONofZWbK7kGQKUAcD3LdtNVuhga056KusjR83tDNdoKizcMlgnDlY95pXphI0shepRITsQHglCdftpW/7H9D3sSkOhrKvQpRYdqrSBNEAnjKf1iugaQImgyqg0RnGYzgyH6aMSHzdZuGQlULJuMWOO3A7Gw='});
    }
  }
  return {requestHeaders: details.requestHeaders};
},{ urls: optUrls }, optExtraInfoSpec);

// 监听长连接dbgj
chrome.runtime.onConnect.addListener(function(port) {
  if (port.name === "dbgj") {
    port.onMessage.addListener(function(request) {
      if (request.action) {
        if (request.action === "getFmdsExtInfo") {
          const dbgjExtInfo = {
            'dbgjExtVersion': chrome.runtime.getManifest().version,
            'dbgjExtId': chrome.runtime.id
          }
          port.postMessage({data: dbgjExtInfo, type: request.type, flag: request.flag});
        }
        else if (request.action === "getSoldHistoryWwPost") {
          $.ajax({
            url: request.url,
            type: "post",
            headers: {
              "Content-type": "application/x-www-form-urlencoded;charset=utf-8"
            },
            data: request.params,
            dataType: 'json',
            success: function (data) {
              port.postMessage({data: data, type: request.type, flag: request.flag, orginData: request.orginData});
            },
            error: function (err) {
              console.log(err);
            }
          });
        }
        else if (request.action === "getOrderDetailsWWGet") {
          $.get(request.url, function (data) {
            try {
                port.postMessage({data: data, type: request.type, flag: request.flag, orginData: request.orginData});
            } catch (err) {
                //
            }
          });
        }
        else if (request.action === "getWeekSellDataGet") {
          $.get(request.url, function (data) {
            try {
              port.postMessage({data: data, type: request.type, flag: request.flag})
            } catch (err) {

            }
          })
        } 
        else if (request.action === "getPunishOrdersGet") {
          getPunishOrdersAjax(request.url, request.params, request.orginData, function(cbdata) {
            port.postMessage({data: cbdata, type: request.type, flag: request.flag})
          });
        }
        else if (request.action === "getRDWwTabsCount") {
          getRDWwTabsCount(function(count) {
            console.log("count"+count)
            port.postMessage({data: count, type: request.type, flag: request.flag});
          });
        }
      } else {
        if(request.type === "post") {
          postAjax(request.url, request.params, function(data) {
            try {
              port.postMessage({
                  data: data,
                  orginData: request.orginData,
                  flag: request.flag,
                  type: request.type
              });
            } catch (err) {
                //
            }
          })
        } else if (request.type === "get") {
          getAjax(request.url, request.params, function(data) {
            try {
              port.postMessage({
                  data: data,
                  flag: request.flag,
                  type: request.type
              });
            } catch (err) {
                //
            }
          });
        }
      }
    })
  }
});